package com.llkj.qingnianguoxue.mine;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.album.AlbumActivity;
import com.llkj.qingnianguoxue.base.BaseActivity;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.IndustryBean;
import com.llkj.qingnianguoxue.bean.ResponseBean;
import com.llkj.qingnianguoxue.customview.OptionsPickerView;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.util.DialogUtil;
import com.llkj.qingnianguoxue.util.FileOperation;
import com.llkj.qingnianguoxue.util.FileProvider7;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.ImageLoadingUtil;
import com.llkj.qingnianguoxue.util.JGuangUtil;
import com.llkj.qingnianguoxue.util.KeyBoardUtil;
import com.llkj.qingnianguoxue.util.PicCameraLocalUtil;
import com.llkj.qingnianguoxue.util.SelectPictureUtil;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.ToastUtil;
import com.llkj.qingnianguoxue.util.Utils;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import rx.functions.Action1;

import static com.llkj.qingnianguoxue.album.AlbumActivity.REQUEST_PICTURES_CODE;

/**
 * 个人信息
 */
public class PersonInfoActivity extends BaseActivity implements View.OnClickListener, DialogUtil.DialogClickListener, DialogUtil.DoWhatData,SelectPictureUtil.SelectPictureResultCallback, /*TimePickerView.OnTimeSelectListener,*/DialogUtil.PickerViewCallback {

    private ImageView ivHead;//头像
    private EditText etName;//名字
    private TextView tvSex, tvBirthday, tvEducation, tvIndustry;//性别，出生日期，学历，行业
    boolean isPermissions;//是否有权限拍照
    private Dialog dialogPhotoPicture;//头像弹框
    private File cameraFile;//

    private int mPickerViewType = 1;//性別，2学历，3行业
    private OptionsPickerView sexPickerView, educationPickerView, industryPickerView;//性別,学历，行业
    private ArrayList<String> sexData, educationData, industryData;//性別,学历，行业
//    private TimePickerView timePickerView;//出生日期
    private OptionsPickerView datePickerView;
    private ArrayList<String> yearData;
    private ArrayList<ArrayList<String>> monthData;
    private ArrayList<ArrayList<ArrayList<String>>> dayData;
    private SelectPictureUtil mSelectPictureUtil;//选择图片

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_info);

        setTitle("个人信息", true, TITLE_TYPE_IMG, R.drawable.icon_back, true, TITLE_TYPE_TEXT, "保存");
        new RxPermissions(this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        isPermissions = aBoolean;
                    }
                });

        initView();
        initListener();

        initViewData();
        HttpMethod.industry(this, this);//学历
    }

    private void initView() {
        initStatusbar(TSATUSBAR_TYPE_BLACK_TEXT,rlTitle,R.color.gray_bar);
        ivHead = (ImageView) findViewById(R.id.iv_head);
        etName = (EditText) findViewById(R.id.et_name);
        tvSex = (TextView) findViewById(R.id.tv_sex);
        tvBirthday = (TextView) findViewById(R.id.tv_birthday);
        tvEducation = (TextView) findViewById(R.id.tv_education);
        tvIndustry = (TextView) findViewById(R.id.tv_industry);

        sexData = new ArrayList<>();
        educationData = new ArrayList<>();
        industryData = new ArrayList<>();
        yearData = new ArrayList<>();
        monthData = new ArrayList<>();
        dayData = new ArrayList<>();
        initPickerViewData();
        sexPickerView = DialogUtil.getOpv(this, sexData, "", this);
        datePickerView = DialogUtil.getDatePicker(this,yearData,monthData,dayData,"",this);

        mSelectPictureUtil = new SelectPictureUtil(this,this);

//        timePickerView = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);
    }

    /**
     * 初始化数据
     */
    private void initViewData(){
        String headUrl = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_HEAD);
        ImageLoadingUtil.loadingImg(ivHead, headUrl, 0);
        String name = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_NAME);
        etName.setText(name);
        String sex = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_SEX);//性別1 男 2 女3 保密
        if("1".equals(sex)){
            sex = "男";
        }else if("2".equals(sex)){
            sex = "女";
        }else{
            sex = "保密";
        }
        tvSex.setText(sex);
        String birtyday = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_BIRTHDAY);
        tvBirthday.setText(birtyday);
        String education = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_EDUCATION);
        tvEducation.setText(education);
        String industry = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_INDUSTRY);
        tvIndustry.setText(industry);
    }

    private void initListener() {
        ivHead.setOnClickListener(this);
        tvSex.setOnClickListener(this);
        tvBirthday.setOnClickListener(this);
        tvEducation.setOnClickListener(this);
        tvIndustry.setOnClickListener(this);
//        timePickerView.setOnTimeSelectListener(this);
    }

    @Override
    protected void rightDoWhat() {
        super.rightDoWhat();
        String name = etName.getText().toString();
        String birthday = tvBirthday.getText().toString();
        String education = tvEducation.getText().toString();
        String industry = tvIndustry.getText().toString();
        String sex = tvSex.getText().toString();
        if("男".equals(sex)){
            sex = "1";
        }else if("女".equals(sex)){
            sex = "2";
        }else{
            sex = "3";
        }

        String nameP = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_NAME);
        String sexP = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_SEX);//性別1 男 2 女3 保密
        String birtydayP = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_BIRTHDAY);
        String educationP = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_EDUCATION);
        String industryP = MyApplication.getInstance().sputil.getString(ConstantUserInfo.USER_INDUSTRY);
        //至少要修改一个信息
        if(cameraFile==null
                && (StringUtils.isEmpty(name) || name.equals(nameP))
                && (StringUtils.isEmpty(sex) || sex.equals(sexP))
                && (StringUtils.isEmpty(birthday) || birthday.equals(birtydayP))
                && (StringUtils.isEmpty(education) || education.equals(educationP))
                && (StringUtils.isEmpty(industry) || industry.equals(industryP))){
            ToastUtil.makeLongText(this,"您沒有修改信息");
            return;
        }
        loadWaitDialog();
        HttpMethod.userEdit(this, this, null,cameraFile, name, birthday, education, industry, sex);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_head://头像
                if (dialogPhotoPicture == null) {
                    dialogPhotoPicture = DialogUtil.showPhotoPictureDialog(this, this);
                }
                KeyBoardUtil.hideSoftKeyboard(this);
                dialogPhotoPicture.show();
                break;
            case R.id.tv_sex://性别
                if (sexData.size() > 0) {
                    mPickerViewType = 1;
                    KeyBoardUtil.hideSoftKeyboard(this);
                    sexPickerView.show();
                }
                break;
            case R.id.tv_birthday://出生日期
//                timePickerView.show();
                KeyBoardUtil.hideSoftKeyboard(this);
                datePickerView.show();
                break;
            case R.id.tv_education://学历
                if (educationData.size() > 0) {
                    mPickerViewType = 2;
                    KeyBoardUtil.hideSoftKeyboard(this);
                    educationPickerView.show();
                }
                break;
            case R.id.tv_industry://行业
                if (industryData.size() > 0) {
                    mPickerViewType = 3;
                    KeyBoardUtil.hideSoftKeyboard(this);
                    industryPickerView.show();
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mSelectPictureUtil.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onCropResult(File file) {
        cameraFile = file;
        String path = cameraFile.getAbsolutePath();
        ivHead.setImageBitmap(null);
        ImageLoadingUtil.loadingCircleBorderImg(ivHead,path, R.color.colorffffff);
    }

    @Override
    public void dialogClick(int type) {
        switch (type) {
            case 1://拍照
                if (isPermissions) {
                    mSelectPictureUtil.takePhoto();
                } else {
                    ToastUtil.makeLongText(this, getResources().getString(R.string.permission_camera));
                }
                break;
            case 2://相册
                mSelectPictureUtil.album();
                break;
        }
    }


    @Override
    public void doone(String data, int options) {
        switch (mPickerViewType) {
            case 1://性别
                tvSex.setText(data);
                break;
            case 2://学历
                tvEducation.setText(data);
                break;
            case 3://行业
                tvIndustry.setText(data);
                break;
        }
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if(method == HttpMethod.HTTP_USER_EDIT){
            ToastUtil.makeLongText(this,"保存成功");
            ResponseBean responseBean = GsonUtil.GsonToBean(data,ResponseBean.class);
            if(cameraFile != null){
                MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_HEAD, cameraFile.getAbsolutePath());
            }

            String name = etName.getText().toString();
            String birthday = tvBirthday.getText().toString();
            String education = tvEducation.getText().toString();
            String industry = tvIndustry.getText().toString();
            String sex = tvSex.getText().toString();
            if("男".equals(sex)){
                sex = "1";
            }else if("女".equals(sex)){
                sex = "2";
            }else{
                sex = "3";
            }

            MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_NAME, name);
            MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_SEX,sex);//性別1 男 2 女3 保密
            MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_BIRTHDAY,birthday);
            MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_EDUCATION,education);
            MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_INDUSTRY,industry);

            if(cameraFile!=null && cameraFile.exists()){
                JGuangUtil.updateUserAvatar(cameraFile);
            }

            JGuangUtil.updateNickName(name);
//            myFinish();
        }else if(method == HttpMethod.HTTP_USER_INDUSTRY){
            IndustryBean industryBean = GsonUtil.GsonToBean(data,IndustryBean.class);
            if(industryBean != null){
                for(int i=0;industryBean.getEducation()!= null && i<industryBean.getEducation().size();i++){//学历
                    educationData.add(industryBean.getEducation().get(i).getEducation());
                }
                for(int i=0;industryBean.getIndustry()!= null && i<industryBean.getIndustry().size();i++){//行业
                    industryData.add(industryBean.getIndustry().get(i).getIndustry());
                }

                educationPickerView = DialogUtil.getOpv(this, educationData, "", this);
                industryPickerView = DialogUtil.getOpv(this, industryData, "", this);
            }
        }
    }

    @Override
    protected void onhttpFailed(String message, int method) {
        super.onhttpFailed(message, method);
        if(!StringUtils.isEmpty(message)){
            ToastUtil.makeLongText(this,message);
        }
    }

    private void initPickerViewData() {
        sexData.add("男");
        sexData.add("女");
        sexData.add("保密");

        Calendar calendar = Calendar.getInstance();
        int curY = calendar.get(Calendar.YEAR);
        for(int i=curY-47;i<curY+10;i++){
            yearData.add(String.valueOf(i));

            ArrayList<String> month = new ArrayList<>();
            monthData.add(month);
            ArrayList<ArrayList<String>> monthD = new ArrayList<>();
            dayData.add(monthD);
            for(int j=1;j<13;j++){
                month.add(String.valueOf(j));

                ArrayList<String> day = new ArrayList<>();
                monthD.add(day);
                for(int k=1;k<32;k++){
                    if((j==4||j==6||j==11||j==9)&&k>30){//30天月份
                        continue;
                    }else if(j==2){
                        if (((i % 4 == 0 && i % 100 != 0) || (i % 400 == 0)) && k>29) {//闰年29天
                            continue;
                        } else if(k>28){//平28天
                            continue;
                        }
                    }
                    day.add(String.valueOf(k));
                }
            }
        }
    }

//    @Override
//    public void onTimeSelect(Date date) {
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//        if (date != null) {
//            try {
//                String d = format.format(date);
//                tvBirthday.setText(d);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//    }

    @Override
    public void pickerBack(String[] data, int[] options) {
        tvBirthday.setText(data[0]+"-"+data[1]+"-"+data[2]);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        File dir = new File(SelectPictureUtil.getAppDir(this), "crop_image");
        FileOperation.deleteFiles(dir);
    }
}
